package com.dongzili.demo.common.config.mybatisplus;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.IService;

public class MybatisPlusUtil {
    /**
     * 获取Service
     */
    public static <T> IService<T> getService(final Class<T> t) {
        DS ds = t.getAnnotation(DS.class);
        if (ds != null){
            DynamicDataSourceContextHolder.push(ds.value());
        }else{
            DynamicDataSourceContextHolder.push("main");
        }
        return SpringUtil.getBean(getBeanName(t) + "AutoServiceImpl");
    }


    /**
     * 获取Mapper
     * @param t
 *     @return
     */
    public static <T> BaseMapper<T> getMapper(final Class<T> t) {
        BaseMapper<T> baseMapper = SpringUtil.getBean(getBeanName(t) + "AutoMapper");
        DS ds = t.getAnnotation(DS.class);
        if (ds != null){
            DynamicDataSourceContextHolder.push(ds.value());
        }else{
            DynamicDataSourceContextHolder.push("main");
        }
//        MybatisMapperProxy<?> mybatisMapperProxy = MybatisUtils.getMybatisMapperProxy(baseMapper);
//        SqlSession sqlSession = mybatisMapperProxy.getSqlSession();
//        System.out.println("Current Database DatabaseId: " + sqlSession.getConfiguration().getDatabaseId());

        return baseMapper;
    }
    /**
     * 获取bean名称
     * @param t
     * @return
     */
    private static <T> String getBeanName(final Class<T> t) {
        return t.getSimpleName().substring(0, 1).toLowerCase() + t.getSimpleName().substring(1);
    }
}